package hr.fer.zpr.nmbp.project3.bll;

import hr.fer.zpr.nmbp.project3.bll.exceptions.BLLException;
import hr.fer.zpr.nmbp.project3.dao.BolestDAO;
import hr.fer.zpr.nmbp.project3.dao.DAOFactory;
import hr.fer.zpr.nmbp.project3.dao.exceptions.DAOException;
import hr.fer.zpr.nmbp.project3.model.Bolest;

import java.util.List;

public class BolestBLL {
	
	private BolestDAO bolestDAO = DAOFactory.getBolestDAO();
    
    public void save(Bolest bolest) {
    	if(!isValidBolest(bolest)){
    		throw new BLLException("Naziv i opis bolesti su obavezna polja");
    	}
    	
    	try{
    		this.bolestDAO.save(bolest);
    	}catch (DAOException e) {
    		throw new BLLException(e.getMessage());
		}
    }
    
    public void update(Bolest bolest){
    	if(!isValidBolest(bolest)){
    		throw new BLLException("Naziv i opis bolesti su obavezna polja");
    	}
    	
    	Bolest proto = new Bolest();
    	proto.setSifra(bolest.getSifra());
    	List<Bolest> bolestiFromDB = this.bolestDAO.load(proto);
    	
    	Bolest persistentBolest;
    	if(bolestiFromDB.size() > 0){
    		persistentBolest = bolestiFromDB.get(0);
    		persistentBolest.setNaziv(bolest.getNaziv());
    		persistentBolest.setOpis(bolest.getOpis());
    	}else{
    		throw new BLLException("Nepostojeća bolest u bazi podataka");
    	}
    	
    	try{
    		this.bolestDAO.save(persistentBolest);
    	}catch (DAOException e) {
    		throw new BLLException(e.getMessage());
		}
    }

    public void delete(Bolest bolest){
    	this.bolestDAO.delete(bolest);
    }
    
    public List<Bolest> loadAll() {
        return bolestDAO.loadAll();
    }
    
    public static boolean isValidBolest(Bolest bolest){
    	if (bolest == null 
				|| bolest.getNaziv() == null
				|| bolest.getNaziv().isEmpty()
				|| bolest.getOpis() == null
				|| bolest.getOpis().isEmpty()) {
			return false;
		}else{
			return true;
		}
    }
}
